import React, { useEffect, useState } from 'react'
import Child from './Child'

export default function App() {
  const [count, setCount] = useState(0)

  const [show, setShow] = useState(true)
  useEffect(() => {
    // 需求: 组件一挂载, 注册全局鼠标移动事件, 打印鼠标位置 => 副作用
    const moveHandle = (e) => {
      console.log(e.pageX, e.pageY)
    }
    window.addEventListener('mousemove', moveHandle)

    // 如何移除全局事件, 清理副作用 => 可以返回一个清理函数(componentWillUnmount)
    return () => {
      // 组件卸载时执行
      console.log('组件卸载了')
      window.removeEventListener('mousemove', moveHandle)
    }
  }, [])

  return (
    <div>
      <h1>计数器-{count}</h1>
      <button
        onClick={() => {
          setCount(count + 1)
        }}
      >
        +1
      </button>
      <hr />
      {show && <Child></Child>}
      <button onClick={() => setShow(!show)}>摧毁组件</button>
    </div>
  )
}
